const byte DATA_PIN = 5; const byte DHT_SUCCESS = 0; const byte DHT_TIMEOUT_ERROR = 1; const byte DHT_CHECKSUM_ERROR = 2; void setup() { Serial.begin(115200); Serial.println(F("Demo DHT11")); pinMode(DATA_PIN, INPUT_PULLUP); } void loop() { float temperature, humidity; switch (readDHT11(DATA_PIN, &temperature, &humidity)) { case DHT_SUCCESS: Serial.print(F("Humidite (%): ")); Serial.println(humidity, 2); Serial.print(F("Temperature (^C): ")); Serial.println(temperature, 2); break; case DHT_TIMEOUT_ERROR: Serial.println(F("No return !")); break; case DHT_CHECKSUM_ERROR: Serial.println(F("Communication error!")); break; } delay(1000); // the DHT11 could make only one mesure by second } byte readDHT11(byte pin, float* temperature, float* humidity) { byte data[5]; byte ret = readDHTxx(pin, data, 18, 1000); if (ret != DHT_SUCCESS) return ret; *humidity = data[0]; *temperature = data[2]; return DHT_SUCCESS; } byte readDHTxx(byte pin, byte* data, unsigned long start_time, unsigned long timeout) { data[0] = data[1] = data[2] = data[3] = data[4] = 0; uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); volatile uint8_t *ddr = portModeRegister(port); volatile uint8_t *out = portOutputRegister(port); volatile uint8_t *in = portInputRegister(port); unsigned long max_cycles = microsecondsToClockCycles(timeout); *out |= bit; *ddr &= ~bit; delay(100); *ddr |= bit; *out &= ~bit; delay(start_time); noInterrupts(); *out |= bit; delayMicroseconds(40); *ddr &= ~bit; timeout = 0; while(!(*in & bit)) { if (++timeout == max_cycles) { interrupts(); return DHT_TIMEOUT_ERROR; } } timeout = 0; while(*in & bit) { if (++timeout == max_cycles) { interrupts(); return DHT_TIMEOUT_ERROR; } } for (byte i = 0; i < 40; ++i) { unsigned long cycles_low = 0; while(!(*in & bit)) { if (++cycles_low == max_cycles) { interrupts(); return DHT_TIMEOUT_ERROR; } } unsigned long cycles_high = 0; while(*in & bit) { if (++cycles_high == max_cycles) { interrupts(); return DHT_TIMEOUT_ERROR; } } data[i / 8] <<= 1; if (cycles_high > cycles_low) { data[i / 8] |= 1; } } interrupts(); byte checksum = (data[0] + data[1] + data[2] + data[3]) & 0xff; if (data[4] != checksum) return DHT_CHECKSUM_ERROR; else return DHT_SUCCESS; }